package com.atom.zx.subscriptions;

import java.util.concurrent.Future;

import com.atom.zx.Subscription;
import com.atom.zx.util.functions.Action0;

/**
 * Helper methods and utilities for creating and working with {@link Subscription} objects
 */
public class Subscriptions {
    /**
     * A {@link Subscription} that does nothing.
     *
     * @return {@link Subscription}
     */
    public static Subscription empty() {
        return EMPTY;
    }

    /**
     * A {@link Subscription} which invokes the given {@link Action0} when unsubscribed.
     *
     * @param unsubscribe Action to invoke on unsubscribe.
     * @return {@link Subscription}
     */
    public static Subscription create(final Action0 unsubscribe) {
        return new Subscription() {

            @Override
            public void unsubscribe() {
                unsubscribe.call();
            }

        };
    }

    /**
     * A {@link Subscription} that wraps a {@link Future} and cancels it when unsubscribed.
     *
     *
     * @param f
     *            {@link Future}
     * @return {@link Subscription}
     */
    public static Subscription create(final Future<?> f) {
        return new Subscription() {

            @Override
            public void unsubscribe() {
                f.cancel(true);
            }

        };
    }

    /**
     * A {@link Subscription} that groups multiple Subscriptions together and unsubscribes from all of them together.
     *
     * @param subscriptions
     *            Subscriptions to group together
     * @return {@link Subscription}
     */

    public static CompositeSubscription create(Subscription... subscriptions) {
        return new CompositeSubscription(subscriptions);
    }

    /**
     * A {@link Subscription} that does nothing when its unsubscribe method is called.
     */
    private static Subscription EMPTY = new Subscription() {
        public void unsubscribe() {
        }
    };
}
